<template>
  <a-breadcrumb style="font-size: 18px; font-weight: bold; margin-bottom: 20px">
    <a-breadcrumb-item>安全管理</a-breadcrumb-item>
    <a-breadcrumb-item>用户管理</a-breadcrumb-item>
  </a-breadcrumb>

  <!-- 查询条件 -->
  <a-form style="margin-bottom: 5px" layout="inline" :model="query">
    <a-form-item>
      <a-select v-model:value="query.u_status" style="width: 100px">
        <a-select-option value="">不限状态</a-select-option>
        <a-select-option value="00">待启用</a-select-option>
        <a-select-option value="55">已启用</a-select-option>
        <a-select-option value="77">已禁用</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item>
      <a-input v-model:value="query.u_id" style="width: 160px">
        <template #prefix>账号：</template>
      </a-input>
    </a-form-item>

    <a-form-item>
      <a-input v-model:value="query.u_name" style="width: 160px">
        <template #prefix>姓名：</template>
      </a-input>
    </a-form-item>

    <a-form-item>
      <a-select v-model:value="query.u_sex" style="width: 100px">
        <a-select-option value="">不限性别</a-select-option>
        <a-select-option value="1">男</a-select-option>
        <a-select-option value="2">女</a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item label="出生日期：">
      <a-date-picker
        v-model:value="query.u_birth_start"
        placeholder="开始日期"
        valueFormat="YYYY-MM-DD"
      />
      至
      <a-date-picker
        v-model:value="query.u_birth_end"
        placeholder="结束日期"
        valueFormat="YYYY-MM-DD"
      />
    </a-form-item>

    <a-form-item>
      <a-button @click="getPage(1)" type="primary"
        ><template #icon><SearchOutlined /></template>查询</a-button
      >
    </a-form-item>
  </a-form>

  <a-space style="margin-bottom: 5px">
    <a-button type="primary" @click="onClickAdd">新增</a-button>
    <a-button type="danger" @click="execDel">删除</a-button>
  </a-space>

  <a-table
    :dataSource="page.list"
    :columns="columns"
    :pagination="pagination"
    @change="handleTableChange"
    :row-selection="rowSelection"
    :row-key="(record) => record.u_id"
  >
    <template #u_sex="{ text }">
      {{ text === 1 ? "男" : text === 2 ? "女" : "未填" }}
    </template>
    <template #u_status="{ text }">
      {{ text === "00" ? "未启用" : text === "55" ? "启用中" : "已禁用" }}
    </template>
    <template #action="{ record }">
      <span>
        <a-button type="link" @click="onClickUpd(record)"
          >修改</a-button
        >
        <a-divider type="vertical" />
        <a-button type="link" @click="execDelSingle(record.u_id)"
          >删除</a-button
        >
        <a-divider type="vertical" />

        <!-- 更多菜单 -->
        <a-dropdown>
          <a class="ant-dropdown-link" @click.prevent>
            更多
            <DownOutlined />
          </a>
          <template #overlay>
            <a-menu @click="onClick">
              <!-- key的组成：操作标识:数据 对于角色菜单key格式： role:u_id,u_name -->
              <a-menu-item :key="'disable:'+record.u_id"  v-if="record.u_status === '55'" >禁用</a-menu-item>
              <a-menu-item :key="'enable:'+record.u_id" v-if="record.u_status === '00' || record.u_status === '77'" >启用</a-menu-item>   
              <a-menu-item :key="'role:'+record.u_id+','+record.u_name" >角色</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>

      </span>
    </template>
  </a-table>

  <user-add ref="userAddRef" @ok="getPage(page.last + 1)"></user-add>

  <user-upd ref="userUpdRef" @ok="getPage(page.current)"></user-upd>

  <user-role ref="userRoleRef" ></user-role>
</template>
<script setup>
import { ExclamationCircleOutlined,DownOutlined  } from "@ant-design/icons-vue";
//引入ref函数，用于构造单向绑定数据
import { ref, reactive, computed, nextTick, createVNode } from "vue";

//引入useRouter函数，用于获取路由器对象
import { useRouter } from "vue-router";

//引入函数，用于向服务端发送get请求
import { get, del, post, getBlob, put, tip, removeLocalToken } from "@/common";

import { Modal } from "ant-design-vue";

//引入搜索图标
import { SearchOutlined } from "@ant-design/icons-vue";

import UserAdd from "./UserAdd.vue";
import UserUpd from "./UserUpd.vue";
import UserRole from "./UserRole.vue"

//获取路由器对象
const router = useRouter();

const userAddRef =  ref();
const onClickAdd = ()=>{
  userAddRef.value.open();
}

const userUpdRef =  ref();
const onClickUpd = (rec)=>{
  userUpdRef.value.open(rec);
}

const columns = [
  {
    title: "账号",
    dataIndex: "u_id",
  },
  {
    title: "姓名",
    dataIndex: "u_name",
  },
  {
    title: "性别",
    dataIndex: "u_sex",
    slots: {
      customRender: "u_sex",
    },
  },
  {
    title: "出生日期",
    dataIndex: "u_birth",
  },
  {
    title: "状态",
    dataIndex: "u_status",
    slots: {
      customRender: "u_status",
    },
  },
  {
    title: "操作",
    key: "action",
    slots: {
      customRender: "action",
    },
  },
];

//分页处理-start
const query = reactive({
  u_id: "",
  u_name: "",
  u_sex: "",
  u_status: "",
  u_birth_start: "",
  u_birth_end: "",
}); //定义查询参数

const page = ref({}); //接收服务端返回的分页对象

//分页引擎
const pagination = reactive({
  current: 1, //当前页
  pageSize: 2, //每页记录数
  total: 0, //总记录数
  pageSizeOptions: ["2", "3", "5", "10", "20", "30", "100"], //每页记录下拉框的选型
  showSizeChanger: true, //是否展示每页记录数下拉框
  showQuickJumper: true, //是否展示快速跳转
  showTotal: (total, range) => {
    //展示总页数等文字说明信息的
    return (
      "共" +
      total +
      "条记录,当前第" +
      pagination.current +
      "页" +
      (range[1] - range[0] + 1) +
      "条记录"
    );
  },
});

//获取当前分页
const getPage = (pageNum = 1) => {
  query.pageNum = pageNum;
  query.pageSize = pagination.pageSize;

  get("/security/user", query).then((res) => {
    page.value = res.data; //将服务端传来的分页数据赋值予page

    //更新分页引擎
    pagination.current = page.value.current;
    pagination.pageSize = page.value.pageSize;
    pagination.total = page.value.total;
  });
};
getPage(1); //页面加载是，首先加载第一页

//当分页发送变化时（如：页码、每页记录数变化时）
const handleTableChange = (pagi, filters, sorter, { currentDataSource }) => {
  pagination.current = pagi.current;
  pagination.pageSize = pagi.pageSize;
  pagination.total = pagi.total;

  getPage(pagination.current);
};

//分页处理-end


const userRoleRef = ref();//用于引用组件UserRole对象
//点击"更多"菜单
const onClick = ({ key }) => {
  const arr = key.split(":");//将字符串按分割符“:”分成若干子串数组
  const flag = arr[0];//操作标识
  const data = arr[1];//数据
  
  switch(flag){
    case 'disable':
      execDisable(data);
      break;
    case 'enable':
      execEnable(data);
      break;
    case 'role':
      //打开角色分配界面
      //角色菜单key格式： role:u_id,u_name
      const tempArr = data.split(",");
      const obj = {
        u_id:tempArr[0],
        u_name:tempArr[1]
      };
      userRoleRef.value.open(obj);
  }
};

// 删除
const selRows = ref([]);
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(selectedRowKeys);
    selRows.value = selectedRows;
  },
  // onSelect: (record, selected, selectedRows) => {
  //   console.log(record, selected, selectedRows);
  // },
  // onSelectAll: (selected, selectedRows, changeRows) => {
  //   console.log(selected, selectedRows, changeRows);
  // },
};

const execDel = () => {
  if (!selRows.value.length) {
    tip.warn("请选择需要删除的数据！");
    return;
  }
  Modal.confirm({
    title: "您确实要删除选中的数据吗？",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确定",
    okType: "danger",
    cancelText: "取消",

    onOk() {
      const ids = [];
      selRows.value.forEach((item) => {
        ids.push(item.u_id);
      });

      del("/security/user", ids).then((res) => {
        getPage(page.value.current);
        tip.success("删除成功！");
      });
    },

    onCancel() {
      tip.info("您已取消删除操作！");
    },
  });
};

const execDelSingle = (uid) => {
  Modal.confirm({
    title: "您确实要删除该数据吗？",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确定",
    okType: "danger",
    cancelText: "取消",

    onOk() {
      del("/security/user/" + uid).then((res) => {
        getPage(page.value.current);
        tip.success("删除成功！");
      });
    },

    onCancel() {
      tip.info("您已取消删除操作！");
    },
  });
};
//执行启用
const execEnable = (uid) => {
  Modal.confirm({
    title: "您确实要启用该用户吗？",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确定",
    okType: "danger",
    cancelText: "取消",

    onOk() {
      put("/security/user/enable/" + uid).then((res) => {
        getPage(page.value.current);
        tip.success("启用成功！");
      });
    },

    onCancel() {
      tip.info("您已取消删除操作！");
    },
  });
};

//执行禁用
const execDisable = (uid) => {
  Modal.confirm({
    title: "您确实要禁用该用户吗？",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确定",
    okType: "danger",
    cancelText: "取消",

    onOk() {
      put("/security/user/disable/" + uid).then((res) => {
        getPage(page.value.current);
        tip.success("禁用成功！");
      });
    },

    onCancel() {
      tip.info("您已取消删除操作！");
    },
  });
};
</script>
<style scoped>
</style>